package d2_udp01;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Server {
    public static void main(String[] args) throws Exception {
        System.out.println(
                "服务端已启动"
        );
        //目标: 开始开发一个服务端程序。(接受数据)
        //1、创建接受端对象, 注册端口(接收端指明的端口)
        DatagramSocket socket = new DatagramSocket(8848);

        //2、创建一个数据包对象(韭菜盘子)
        byte[] buffer = new byte[1024 * 64];
        DatagramPacket packet = new DatagramPacket(buffer,buffer.length);

        //3、接受数据(接受韭菜)
        socket.receive(packet);//暂停等待,进行接受数据

        //4、把数据输出
        //获取本轮收到多少个字节
        int len = packet.getLength();

        //进行解码
        //接受多少进行倒多少
        //如果不装满,有不接受多少,倒多好,就会显示很多0字节的,
        String message = new String(buffer, 0, len);

        System.out.println(message);
        //获取发送端的IP和端口
        InetAddress ip = packet.getAddress();
//        System.out.println(InetAddress.getLocalHost());

        System.out.println("对方ip: " + ip.getHostAddress());
        System.out.println("对方端口:" + packet.getPort());


        //5、进行释放资源
        socket.close();

    }
}
